/*
 * Copyright 2008 Wink Saville
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.saville.hmc;

import android.os.Looper;
import com.saville.debug.Log;
import com.saville.msgcomp.*;
import com.saville.mc.*;

abstract public class ActiveHmc extends Hmc implements IActiveMc, Runnable {
    /*
     * Constructor
     */
    public ActiveHmc(String name, int numStates, int initialState) {
        /* Don't call Mc#init until after our thread is going */
        super(name, numStates, initialState, false);

        Log.d(df, "%s: ActiveHmc() E", mName);

        Thread thr = new Thread(null, this, mName);
        thr.start();

        while (mRunning != 1) {
            sleep(100);
        }

        /* Now call Mc#init that we have our looper going */
        init(name, mMsgPump, false);

        Log.d(df, "%s: ActiveHmc() X", mName);
    }

    public void run() {
        Log.d(df, "ActiveMc: %s run() E", mName);
        Looper.prepare();
        mMsgPump = new MsgPump(Looper.myLooper());
        mRunning = 1;
        Looper.loop();
        Log.d(df, "ActiveMc: %s run() X", mName);
    }

    private void sleep(int millisecs) {
        try {
            Thread.sleep(millisecs);
        } catch (InterruptedException e) {
        }
    }

    protected volatile int mRunning;
    protected MsgPump mMsgPump;
}
